<style lang="less">
     @import './index.less';
</style>

<template>
  <div>
    <Button icon="reply" type="text" @click="goForward">上一步</Button>
    <Card>
      <Row :gutter="10">
        <i-col span="18">
          <div style="padding:10px">
            <h2>{{contractMes.contract_name}}
              <Tag color="blue" type="border" class="margin-left-10 margin-bottom-8">{{contractMes.status}}</Tag>
            </h2>
            <p>总金额：{{contractMes.contract_amount}}元</p>
            <p>起止时间：{{contractMes.contract_start_date}} 至 {{contractMes.contract_end_date}}</p>
          </div>
        </i-col>
        <i-col span="6" class="margin-top-15">
          <detailModifyBtn @modifyClick="modify" :status="status" :creator="creator"></detailModifyBtn>
          <detailDeleteBtn @deleteClick="del(contractMes.contract_id,contractMes.contract_name)" :status="status" :creator="creator"></detailDeleteBtn>
        </i-col>
      </Row>
    </Card>
    <Row :gutter="10" class="margin-top-10">
      <i-col span="17">
        <Card dis-hover>
          <Tabs value="1">
              <TabPane label="基本信息" name="1">
                <div class="division-tips">
                  <span>
                    <Icon type="arrow-down-b" size="12" class="padding-left-10 margin-right-10"></Icon>
                    基本信息
                  </span>
                </div>
                <div class="box">
                    <Row>
                      <i-col span="12">
                        <p>合同状态：{{contractMes.status}}</p>
                      </i-col>
                      <i-col span="12">
                        <p>合同金额：{{contractMes.contract_amount}}</p>
                      </i-col>
                    </Row>
                    <Row>
                      <i-col span="12">
                        <p>合同开始日期：{{contractMes.contract_start_date}}</p>
                      </i-col>
                      <i-col span="12">
                        <p>合同结束日期：{{contractMes.contract_end_date}}</p>
                      </i-col>
                    </Row>
                  </div>
                <div class="division-tips">
                    <span>
                      <Icon type="arrow-down-b" size="12" class="padding-left-10 margin-right-10"></Icon>
                      其他信息
                    </span>
                </div>
                <div class="box">
                  <Row>
                    <i-col span="12">
                      <p>合同申请时间：{{contractMes.contract_date}}</p>
                    </i-col>
                    <i-col span="12">
                      <p>备注：{{contractMes.remark}}</p>
                    </i-col>
                  </Row>
                  <Row>
                    <i-col span="12">
                      <p>合同签订时间：<span v-show="contractMes.status === '已归档'">{{contractMes.update_time}}</span></p>
                    </i-col>
                  </Row>
                </div>
              </TabPane>
              <TabPane label="产品信息" name="2">
                <Table :columns="productsColumns" :data="contractMes.sales"></Table>                
              </TabPane>
              <TabPane label="回款信息" name="3">
                <div class="division-tips">
                  <span>
                    <Icon type="arrow-down-b" size="12" class="padding-left-10 margin-right-10"></Icon>
                    应收周期
                  </span>
                </div>
                <Table :columns="receivablesPlanColumns" :data="contractMes.receivables"></Table>
                <div class="division-tips margin-top-10">
                  <span>
                    <Icon type="arrow-down-b" size="12" class="padding-left-10 margin-right-10"></Icon>
                    回款记录
                  </span>
                </div>
                <Table :columns="backpaymentColumns" :data="backpaymentData"></Table>
              </TabPane>
              <TabPane label="审核记录" name="6">
                <Table :columns="flowColumns" :data="flowData"></Table>
              </TabPane>
              <TabPane label="附件" name="5">
                <div class="division-tips margin-top-10" v-show="contractMes.oss_name">
                  <Button type="text" @click="downloadFile(contractMes.oss_id)">{{contractMes.oss_name}}</Button>
                </div>
                <div class="division-tips margin-top-10" v-show="contractMes.contract_profile_name">
                  <Button type="text" @click="downloadFile(contractMes.contract_profile_id)">{{contractMes.contract_profile_name}}</Button>
                </div>
              </TabPane>
          </Tabs>
        </Card>
      </i-col>
      <i-col span="7">
        <Card dis-hover>
          <Tabs value="1">
              <TabPane label="追踪" name="1">
                <p>追踪里的内容</p>
              </TabPane>
              <TabPane label="团队成员" name="2">
                <p>团队成员里的内容</p>
              </TabPane>
          </Tabs>
        </Card>
      </i-col>
    </Row>
    <Modal v-model="modifyModal" width="1000" title="修改合同" :loading="loading" @on-ok="submitModify('modifyModal')" @on-cancel="cancel('modifyModal')">
      <Form ref="modifyModal" :model="modifyForm" :rules="ruleValidate" label-position="left" :label-width="100">
        <Tabs value="1">
          <TabPane label="基本信息" name="1">
            <Row :gutter="15">
              <i-col span="10" offset="1">
                <FormItem label="客户名称:" prop="customer_id">
                  <Select v-model="modifyForm.customer_id" transfer>
                    <Option v-for="item in companyList" :key="item.contract_id" :value="item.customer_id">{{item.customer_name}}</Option>
                  </Select>
                </FormItem>
              </i-col>
              <i-col span="10" offset="1">
                <FormItem label="合同负责人:" prop="responsible">
                  <Select v-model="modifyForm.responsible" transfer>
                    <Option v-for="item in employeeList" :key="item.responsible" :value="item.responsible">{{item.employee_name}}</Option>
                  </Select>
                </FormItem>
              </i-col>
            </Row>
            <Row :gutter="15">
              <i-col span="10" offset="1">
                <FormItem label="合同名称:">
                  <Input type="text" v-model="modifyForm.contract_name"></Input>
                </FormItem>
              </i-col>
              <i-col span="10" offset="1">
                <FormItem label="合同类型:">
                  <Select v-model="modifyForm.type">
                    <Option value="收入">收入</Option>
                  </Select>
                </FormItem>
              </i-col>
            </Row>
            <Row :gutter="15">
              <i-col span="10" offset="1">
                <FormItem label="合同开始时间:">
                  <DatePicker type="date" ref="contractStart" transfer placement="bottom-start" :value="modifyForm.contract_start_date" @on-change="setContractStart"></DatePicker>
                </FormItem>
              </i-col>
              <i-col span="10" offset="1">
                <FormItem label="合同结束时间">
                  <DatePicker type="date" ref="contractEnd" transfer placement="bottom-start" :value="modifyForm.contract_end_date" @on-change="setContractEnd"></DatePicker>
                </FormItem>
              </i-col>
            </Row>
            <Row :gutter="15">
              <i-col span="10"  offset="1">
                <FormItem label="签约日期:">
                  <DatePicker type="date" ref="contractSign" transfer placement="bottom-start" :value="modifyForm.contract_date" @on-change="setContractSign"></DatePicker>            
                </FormItem>
              </i-col>
              <i-col span="10" offset="1">
                <FormItem label="备注">
                  <Input type="textarea" v-model="modifyForm.remark"></Input>
                </FormItem>
              </i-col>
            </Row>
            <Row :gutter="15">
              <i-col span="10" offset="1">
                <FormItem label="合同附件">
                  <Upload 
                      ref="upload"
                      name="file"
                      :headers="{Authorization: 'Bearer' + token}"
                      :action=" this.util.ajaxUrl.file +'/sys/files '"
                      :on-success="handleFileSuccess"
                      :on-remove="removeFile">
                      <Button type="ghost" icon="ios-cloud-upload-outline">选择上传的合同附件</Button>
                    </Upload>
                </FormItem>
              </i-col>
            </Row>
          </TabPane>
          <TabPane label="产品信息" name="2">
            <div v-for="(item,index) in modifyForm.sales" :key="index" class="dotted-box">
              <Row :gutter="15">
                <i-col span="16" offset="1">
                  <FormItem label="产品名称" :prop="'sales.' + index + '.product_id'" :rules="{required: true, message: '请选择产品', trigger: 'blur'}">
                    <Select v-model="item.product_id" @on-change="(id) => getProductInfo(id,index)">
                      <Option v-for="item in productList" :key="item.product_id" :value="item.product_id">{{item.product_name}}</Option>
                    </Select>
                  </FormItem>
                </i-col>
              </Row>
              <Row>
                <i-col span="5" offset="1">
                  <FormItem label="单价:" :label-width="50">
                    <span>{{item.price}} 元</span>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="数量:" :label-width="50">
                    <Button type="text" icon="minus-round" class="margin-right-10" @click="sub(item,index)"></Button>
                    <strong >{{item.quantity}}</strong>
                    <Button type="text" icon="plus-round" class="margin-left-10" @click="add(item,index)"></Button>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="总价:" :label-width="50">
                    <span>{{item.totalSum}}</span>
                  </FormItem>
                </i-col>
                <i-col span="5">
                  <FormItem label="优惠价:" :label-width="60">
                    <Input type="text" size="small" v-model="item.amount" @on-change="changeSum"></Input>
                  </FormItem>
                </i-col>
                <i-col span="2" pull="1">
                  <FormItem>
                    <Button type="text" icon="trash-a" v-show="index !== 0" @click="removeSales(index)"></Button>
                  </FormItem>
                </i-col>
              </Row>
            </div>
            <Row>
              <i-col span="4" offset="4">
                  <Button type="dashed" icon="plus" @click="addSales">添加更多产品信息</Button>
              </i-col>
            </Row>
            <Row>
              <i-col span="5" offset="16">
                <FormItem label="合同金额:" class="pull-right">
                  <strong style="font-size:16px">{{sum}}</strong> 元
                </FormItem>
              </i-col>
            </Row>
          </TabPane>
          <TabPane label="应收周期" name="3">
            <Row v-for="(item,index) in modifyForm.receivables" :key="index" type="flex" justify="space-around">
              <i-col span="7">
                <FormItem label="应收期次:">
                  <Input v-model="item.count"></Input>                      
                </FormItem>
              </i-col>
              <i-col span="7">
                <FormItem label="应收截止时间:">
                  <DatePicker type="date" transfer :value="item.receivable_date" @on-change="(date) => setReceivableDate(date,index)"></DatePicker>
                </FormItem>
              </i-col>
              <i-col span="7">
                <FormItem label="应收金额:">
                  <Input v-model="item.receivable_amount"  @on-change="changeReceivableMoney"></Input>                      
                </FormItem>
              </i-col>
              <i-col span="1" pull="2">
                <FormItem>
                  <Button type="text" icon="trash-a" v-show="index !== 0" @click="removeReceivalbe(index)"></Button>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col span="4" offset="4">
                  <Button type="dashed" icon="plus" @click="addReceivalbe">添加应收周期</Button>
              </i-col>
            </Row>
            <Row>
              <i-col span="5" push="17">
                  <span>总应收金额: <strong style="font-size:16px">{{receivableSum}}</strong> 元</span>
                  <div v-show="receivableSum !== sum" class="ivu-form-item-error-tip">应收总额应与合同总金额相等</div>
              </i-col>
            </Row>
          </TabPane>
        </Tabs>
      </Form>
    </Modal>
  </div>
</template>

<script>
import detailModifyBtn from './component/access-detail-modify-button.vue';
import detailDeleteBtn from './component/access-detail-delete-button.vue';
import util from "@/libs/util";


export default {
  data() {
    return {
      util:util,
      companyList:[],
      employeeList:[],
      productList:[],
      flowData:[],
      backpaymentData:[],
      contractMes:{},
      receivableSum:0,
      sum:0,
      modifyModal:false,
      status:'',
      creator:'',
      loading:true,
      modifyForm:{
        sales:[{quantity:1}],
        receivables:[{}]
      },
      columns1: [
        {
          title: '序号',
          type: 'index',
          align:'center',
          width:60
        },
        {
          title: '时间(约定的还款时间)',
          key: 'time',
          align:'center'
        },
        {
          title: '可确认收入（单位：万元）（应收）',
          align:'center',
          key: 'receivable'
        },
        {
          title: '回款金额（单位：万元）（实收）',
          align:'center',
          key: 'realIncome'
        },
        {
          title: '款额状态',
          align:'center',
          key: 'status',
          render:(h,params) => {
            if(params.row.realIncome < params.row.receivable) {
              return h('span',{
                style:{
                  color:'#ed3f14'
                }
              },'异常')
            }else{
              return h('span',{},'正常')
            }
          }
        }
      ],
      productsColumns:[
        {
          title: '序号',
          type: 'index',
          align:'center',
        },{
          title:'产品名称',
          key:'product_name',
          align:'center'
        },{
          title:'单价',
          key:'price',
          align:'center'
        },{
          title:'数量',
          key:'quantity',
          align:'center'
        },{
          title:'优惠金额',
          key:'amount',
          align:'center'
        }
        // ,{
        //   title:'合计',
        //   key:'amount',
        //   align:'center'
        // }
      ],
      data1:[
        {
          time:'2018-01-30',
          fileName:'合同模版',
        },
        {
          time:'2018-02-28',
          fileName:'归档合同',
        }
      ],
      columns3: [
        {
          title:'审核时间',
          key:'time',
          align:'center'
        },{
          title:'审核结果',
          key:'result',
          align:'center'
        }
      ],
      receivablesPlanColumns:[
        {
          title:'应收单号',
          align:'center',
          render:(h,params) => {
            if(params.row.contract_number && params.row.count) {
              return h('span',{},params.row.contract_number + '-' + params.row.count)
            }else {
              return h('span',{},'暂无应收单号')
            }
          }
        },{
          title:'应收金额',
          align:'center',
          key:'receivable_amount'
        },{
          title:'应收时间',
          align:'center',
          key:'receivable_date'
        },
      ],
      backpaymentColumns:[
        {
          title:'回款单号',
          align:'center',
          render:(h,params) => {
            return h('span',{},params.row.contract_number + '-' + params.row.receivable_count)
          }
        },{
          title:'回款金额',
          align:'center',
          key:'backpayment_amount'
        },{
          title:'回款时间',
          align:'center',
          key:'backpayment_date'
        }
      ],
      filesColumns:[
        {
          title:'文档名称',
          align:'center',
          key:'fileName'
        },{
          title:'创建时间',
          align:'center',
          key:'time'
        }
      ],
      flowColumns:[
        {
          title:'序号',
          align:'center',
          type:'index'
        },{
          title:'审核时间',
          align:'center',
          key:'approvalDate'
        },{
          title:'审核人',
          align:'center',
          key:'approvalUserId'
        },{
          title:'审核意见',
          align:'center',
          key:'comment'
        },{
          title:'审核结果',
          align:'center',
          key:'action'
        }
      ],
      ruleValidate: {
        customer_id:[
           { required: true, message: '请选择客户', trigger: 'blur' }
        ],
        responsible:[
           { required: true, message: '请选择合同负责人', trigger: 'blur' }
        ]
      },
  }
  },
  methods: {
    goForward() {
      this.$router.go(-1)
    },
    getContract() {
      this.$http.get('/fi/contracts/' + this.contract_id).then((res) => {
        this.contractMes = res.data.returnValue
        this.contractMes.update_time = this.contractMes.update_time.split(' ')[0]
        _.forEach(this.contractMes.sales,item => {
          item['totalSum'] = item.price * item.quantity
        })
        _.forEach(this.contractMes.receivables,item => {
          item['contract_number'] = this.contractMes.contract_number
        })
      })
    },
    getCompanys() {
      this.$http.get('/customer/customers').then((res) => {
        this.companyList = res.data.returnValue
      })
    },
    getEmployees() {
      this.$http.get('/fi/hr/employeelist?org_id=').then((res) => {
        this.employeeList = res.data
      })
    },
    getProducts() {
      this.$http.get('/fi/sale/products').then((res) => {
        this.productList = res.data.returnValue
      })
    },
    getFolw() {
      this.$flowHttp.get('/flow/history?category=contract-approval&key=' + this.contract_id).then((res) => {
        this.flowData = res.data.returnValue
      })
    },
    getBackpayment() {
      this.$http.get('/fi/backpayments?contract_id='+this.contract_id+'&contract_number=&customer_id=&start=&end=').then((res) => {
        this.backpaymentData = res.data.returnValue
      })
    },
    setContractStart(date) {
      this.modifyForm.contract_start_date = date
    },
    setContractEnd(date) {
      this.modifyForm.contract_end_date = date
    },
    setContractSign(date) {
      this.modifyForm.contract_date = date
    },
    setReceivableDate(date,index) {
      this.modifyForm.receivables[index].receivable_date = date
    },
    addSales() {
      this.modifyForm.sales.push({quantity:1})
    },
    cleanDatePicker() {
      this.$refs.contractStart.handleClear()
      this.$refs.contractEnd.handleClear()
      this.$refs.contractSign.handleClear()
    },
    handleFileSuccess(res) {
      if (res.success) {
        this.$Message.success('文件上传成功')
        this.createForm.oss_id = res.returnValue;
      } else {
        this.$Message.error('图片上传失败,请重试');
      }
    },
    removeFile(){
      this.$refs['upload'].clearFiles()
    },
    getProductInfo(id,index) {
      console.info(id,index)
      console.info(_.findIndex(this.productList,{product_id:id}))
      if(id && index) {
        this.modifyForm.sales[index].price = this.productList[_.findIndex(this.productList,{product_id:id})].price // 单价
        this.modifyForm.sales[index].totalSum = parseFloat(this.modifyForm.sales[index].price * this.modifyForm.sales[index].quantity) // 当前商品价格
      }
      //console.info(this.productList[_.findIndex(this.productList,{product_id:id})])
    },
    add(item,index) {
      item.quantity++
      this.getProductInfo(item.product_id,index)
    },
    sub(item,index) {
      item.quantity--
      if(item.quantity <= 1){
        item.quantity = 1
      }
      this.getProductInfo(item.product_id,index)
    },
    addSales() {
      this.modifyForm.sales.push({quantity:1})
    },
    removeSales(index) {
      this.modifyForm.sales.splice(index,1)
      this.changeSum()
    },
    addReceivalbe() {
      this.modifyForm.receivables.push({})
    },
    removeReceivalbe(index) {
      this.modifyForm.receivables.splice(index,1)
    },
    changeSum() {
      var sum = 0
      _.forEach(this.modifyForm.sales,item => {
        if(item.amount.length !== 0) {
          sum = sum + parseFloat(item.amount)
        }else {
          sum = sum + item.amount
        }
      })
      this.sum = parseFloat(sum)
    },
    changeReceivableMoney() {
      var sum = 0
      _.forEach(this.modifyForm.receivables,item => {
          if(item.receivable_amount.length !== 0) {
            sum = sum + parseFloat(item.receivable_amount)
          }else {
            sum = sum + item.receivable_amount
          }
        })
        this.receivableSum = parseFloat(sum)
    },
    modify() {
      this.getCompanys()
      this.getEmployees()
      this.getProducts()
      this.modifyForm = _.cloneDeep(this.contractMes)
      this.modifyModal = true
    },
    submitModify(name) {
      this.$refs[name].validate((valid) => {
        if(valid) {
          this.$http.put('/fi/contracts',this.modifyForm).then((res) => {
            this.$Message.success('修改成功')
            this.modifyModal = false
            this.getContract()
          }).catch(() => {
            this.$Message.error('修改失败，请稍后重试')
          })
        }else {
          this.$Message.info('请检查所有必填字段')
          this.loading = false
          this.$nextTick(() => {
            this.loading = true
          })
        }
      })
    },
    cancel(name) {
      this.$refs[name].resetFields()
    },
    del(id,name) {
      this.$Modal.confirm({
        title: '确认',
        content: '确认要删除【' + name + '】合同吗？',
        onOk: () => {
          this.deleteHandel(id);
        }
      })
    },
    deleteHandel(id) {
      this.$http.delete('/fi/contracts/'+ id).then((res) => {
        this.$Message.success('删除成功！')
        this.goForward()
      }).catch(() => {
        this.$Message.error('删除失败，请重试！')
     })
    },
    downloadFile(id) {
      window.location.href = this.util.ajaxUrl.file + '/sys/files/' + id
    }
  },
  computed: {
    token: {
      get() {
        return this.$auth.token()
      }
    }
  },
  components: {
    detailModifyBtn,
    detailDeleteBtn
  },
  mounted() {
    this.contract_id = this.$route.params.id
    this.status = this.$route.params.status
    this.creator = this.$route.params.creator
    this.getContract()
    this.getFolw()
    this.getBackpayment()
  }
}
</script>

